package com.ctgu.demo.controller;

import com.ctgu.demo.utils.ApiResult;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.PostConstruct;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/opsForList")
public class OpsForListController {

    private final RedisTemplate<String, String> redisTemplate;

    public OpsForListController(RedisTemplate<String, String> redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    private static final String STACK_KEY = "ctgu:stack:1001";
    private static final String QUEUE_KEY = "ctgu:queue:1001";
    private static final List<String> list = Arrays.asList("A", "B", "C", "D", "E");

    // 容器启动时初始化栈和队列
    @PostConstruct
    public void init() {
        // 初始化栈
        redisTemplate.delete(STACK_KEY);
        for (String action : list) {
            redisTemplate.opsForList().rightPush(STACK_KEY, action);
        }

        // 初始化队列
        redisTemplate.delete(QUEUE_KEY);
        for (String action : list) {
            redisTemplate.opsForList().rightPush(QUEUE_KEY, action);
        }
    }

    // http://localhost:8080/opsForList/stack
    // 栈：Redis 列表可以用作栈。使用 rpush 和 lpop 或 lpush 和 rpop 可以实现栈的操作。
    @GetMapping("stack")
    public ApiResult stack() {
        String lastAction = redisTemplate.opsForList().rightPop(STACK_KEY);
        if (lastAction == null) {
            return ApiResult.error("栈已空");
        }
        Map<String, Object> result = new HashMap<>();
        result.put("action", lastAction);
        return ApiResult.success("获取栈成功", result);
    }

    // http://localhost:8080/opsForList/queue
    // 队列：Redis 列表也可以用作队列。使用 lpush 和 rpop 或 rpush 和 lpop 可以实现队列的功能。
    @GetMapping("queue")
    public ApiResult queue() {
        String processingOrder = redisTemplate.opsForList().leftPop(QUEUE_KEY);
        if (processingOrder == null) {
            return ApiResult.error("队列已空");
        }
        Map<String, Object> result = new HashMap<>();
        result.put("action", processingOrder);
        return ApiResult.success("获取队列成功", result);
    }
}